package com.primb.bench.project.home.presenter;

import android.content.Context;
import android.content.Intent;

import com.orhanobut.logger.Logger;
import com.primb.baselibs.util.FormatUtils;
import com.primb.bench.R;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.project.approval.entity.NextPersonEntity;
import com.primb.bench.project.home.contract.LoanCalculateContract;
import com.primb.bench.project.home.entity.ApplyNextUserEntity;
import com.primb.bench.project.home.entity.ClientInfoEntity;
import com.primb.bench.project.home.entity.EnsureInfoEntity;
import com.primb.bench.project.home.entity.HttpApplyResultEntity;
import com.primb.bench.project.home.entity.HttpCheckProEntity;
import com.primb.bench.project.home.entity.HttpLogoEntity;
import com.primb.bench.project.home.entity.HttpResultEntity;
import com.primb.bench.project.home.entity.HttpStrEntity;
import com.primb.bench.project.home.entity.LoanCalculateInfoEntity;
import com.primb.bench.project.home.entity.LoanInfoEntity;
import com.primb.bench.project.home.entity.LogoInfoEntity;
import com.primb.bench.project.home.entity.PromiseApplyEntity;
import com.primb.bench.project.home.entity.TaxInfoEntity;
import com.primb.bench.project.home.model.LoanCalculateModelImpl;
import com.primb.netlibs.exception.ApiException;

import java.util.Date;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

import static com.primb.bench.common.constant.AppConstant.USER_NAME;
import static com.primb.bench.common.constant.AppConstant.USER_NAME_ID;
import static com.primb.bench.common.constant.AppConstant.USER_PART_ID;
import static com.primb.bench.common.constant.AppConstant.USER_PART_NAME;
import static com.primb.bench.project.home.activity.LoanCalculateActivity.KEY_PRICE_MEASURE;

/**
 * Created by Administrator on 2017/05/05
 */

public class LoanCalculatePresenterImpl implements LoanCalculateContract.Presenter {

    private LoanCalculateContract.View mView;
    private LoanCalculateModelImpl mModel;
    private CompositeSubscription subscription;
    public LoanCalculateInfoEntity infoEntity;
    private String sceneType;
    private String priceType;
    private Context context;

    public LoanCalculatePresenterImpl(Context context, LoanCalculateContract.View mView) {
        this.mView = mView;
        this.context = context;
        mModel = new LoanCalculateModelImpl();
        subscription = new CompositeSubscription();
        infoEntity = new LoanCalculateInfoEntity();
    }

    @Override
    public void getLogoInfo() {
        mView.showLoading();
        Subscription subscribe = mModel.getLogoInfo().subscribe(new HttpSubscriber<HttpLogoEntity>(context) {
            @Override
            public void onError(ApiException e) {
                mView.showError(e.getMessage());
                mView.hideLoading();
            }

            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onNext(HttpLogoEntity httpLogoEntity) {
                LogoInfoEntity logoInfoEntity = new LogoInfoEntity();
                logoInfoEntity.setLogoDate(FormatUtils.DATE_FORMAT.format(new Date()));
                logoInfoEntity.setLogoManagerName(USER_NAME);
                logoInfoEntity.setLogoManagerNum(USER_NAME_ID);
                logoInfoEntity.setLogoNumber(httpLogoEntity.getData().getPriceId());
                logoInfoEntity.setLogoPart(USER_PART_NAME);
                logoInfoEntity.setLogoPartId(USER_PART_ID);
                logoInfoEntity.setLogoProtocolType(sceneType);
                logoInfoEntity.setLogoPriceType(priceType);
                // TODO: 2017/7/27
                logoInfoEntity.setLogoProtocolNum("");
                infoEntity.setLogoInfoEntity(logoInfoEntity);
                mView.setInfoToLogo(logoInfoEntity);

                TaxInfoEntity taxInfoEntity = new TaxInfoEntity();
                taxInfoEntity.setTaxVat(httpLogoEntity.getData().getAddValueTax());
                taxInfoEntity.setTaxIncome(httpLogoEntity.getData().getLnIncomeTax());
                infoEntity.setTaxInfoEntity(taxInfoEntity);

                mView.setInfoToTax(taxInfoEntity);

                mView.showCustomerAddInfo();
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public void setLogoType(String type, String priceType) {
        this.sceneType = type;
        this.priceType = priceType;
    }


    @Override
    public void getResultForAddInfo(int requestCode) {
        Logger.e("获取的结果" + requestCode);
    }

    @Override
    public void saveResult() {
        mView.showLoading();
        Subscription subscribe = mModel.saveResult(infoEntity).subscribe(new HttpSubscriber<HttpStrEntity>(context) {
            @Override
            public void onError(ApiException e) {
                mView.showError(e.getMessage());
                mView.hideLoading();
            }

            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onNext(HttpStrEntity bean) {
                if (bean.isSuccess()) {
                    mView.intentToMain();
                    mView.showError(bean.getData());
                } else {
                    mView.showError(bean.getMsg());
                }
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public void getCalculateResult(LoanCalculateInfoEntity infoEntity) {
        mView.getInfoToTax(infoEntity.getTaxInfoEntity());
        if (infoEntity.getLoanInfoEntity().isLoanInfoEmpty()) {
            mView.showError("贷款信息未完善,请完善后重试");
            return;
        }
        if (infoEntity.getEnsureInfoEntity().isEnsureInfoEmpty()) {
            mView.showError("担保信息未完善,请完善后重试");
            return;
        }
        if (infoEntity.getClientInfoEntity().isCustomerInfoEmpty()) {
            mView.showError("客户信息未完善,请完善后重试");
            return;
        }
        mView.showLoading();
        Subscription subscribe = mModel.getLoanCalculate(infoEntity).subscribe(new HttpSubscriber<HttpResultEntity.DataBean>(context) {

            @Override
            public void onError(ApiException e) {
                mView.showError(e.getMessage());
                mView.hideLoading();
            }

            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onNext(HttpResultEntity.DataBean bean) {
                infoEntity.setResultInfoEntity(bean);
                PromiseApplyEntity promiseApplyEntity = new PromiseApplyEntity();
                promiseApplyEntity.setPromiseAdjustDirectRate(bean.getLnpTargetRate());
                infoEntity.setPromiseApplyEntity(promiseApplyEntity);
                mView.showResultView(bean);
                if (priceType.equals(KEY_PRICE_MEASURE)) {
                    mView.showApplyView();
                }
                mView.closeTaxEdit();
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public void handleResultInfo(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case AppConstant.LOAN_CUSTOMER_REQUEST:
                if (resultCode == AppConstant.LOAN_CUSTOMER_RESULT) {
                    ClientInfoEntity info = data.getParcelableExtra("info");
                    if (infoEntity.getClientInfoEntity() != null &&
                            !infoEntity.getClientInfoEntity().getCustomerType().equals(info.getCustomerType())) {
                        infoEntity.setClientInfoEntity(info);
                        mView.changeCustomerInfo();
                        mView.setInfoToCustomer(info);
                        infoEntity.setEnsureInfoEntity(null);
                        infoEntity.setLoanInfoEntity(null);
                    } else {
                        mView.showCustomerInfo();
                        infoEntity.setClientInfoEntity(info);
                        mView.setInfoToCustomer(info);
                    }
                }
                break;
            case AppConstant.LOAN_LOAN_REQUEST:
                if (resultCode == AppConstant.LOAN_LOAN_RESULT) {
                    mView.showLoanInfo();
                    LoanInfoEntity info = data.getParcelableExtra("info");
                    infoEntity.setLoanInfoEntity(info);
                    mView.setInfoToLoan(info);
                }
                break;
            case AppConstant.LOAN_ENSURE_REQUEST:
                if (resultCode == AppConstant.LOAN_ENSURE_RESULT) {
                    EnsureInfoEntity info = data.getParcelableExtra("info");
                    infoEntity.setEnsureInfoEntity(info);
                    mView.setInfoToEnsure(info);
                    mView.setInfoToTax(infoEntity.getTaxInfoEntity());

                    mView.showEnsureInfo();
                    mView.showTaxInfo();
                }
                break;
            case AppConstant.LOAN_TAX_REQUEST:
                if (resultCode == AppConstant.LOAN_TAX_RESULT) {
                    TaxInfoEntity info = data.getParcelableExtra("info");
                    infoEntity.setTaxInfoEntity(info);
                    mView.setInfoToTax(info);
                }
                break;
            case AppConstant.LOAN_PROMISE_REQUEST:
                if (resultCode == AppConstant.LOAN_PROMISE_RESULT) {
                    PromiseApplyEntity info = data.getParcelableExtra("info");
                    info.setPromiseDetail(true);
                    mView.setInfoToPromise(info);
                    mView.closePromiseEdit();
                    if (priceType.equals(KEY_PRICE_MEASURE)) {
                        mView.showApplyView();
                    }
                    infoEntity.setPromiseApplyEntity(info);
                }
                break;
        }
    }

    @Override
    public void onViewClick(int viewId, boolean isShowResult) {
        switch (viewId) {
            case R.id.iv_top:
                mView.resetView();
                break;
//            case R.id.iv_logo_edit:
//                mView.intentToAddInfo(AppConstant.LOAN_LOGO_REQUEST);
//                break;
            case R.id.btn_calculate_measure:
                getCalculateResult(infoEntity);
                break;
            case R.id.layout_calculate_customer:
                if (!isShowResult)
                    mView.intentToAddInfo(AppConstant.LOAN_CUSTOMER_REQUEST);
                break;
            case R.id.layout_calculate_loan:
                if (!isShowResult)
                    mView.intentToAddInfo(AppConstant.LOAN_LOAN_REQUEST);
                break;
            case R.id.layout_calculate_ensure:
                if (!isShowResult)
                    mView.intentToAddInfo(AppConstant.LOAN_ENSURE_REQUEST);
                break;
//            case R.id.layout_calculate_tax:
//                if (!isShowResult)
//                    mView.intentToAddInfo(AppConstant.LOAN_TAX_REQUEST);
//                break;
            case R.id.btn_calculate_promise:
                checkPromise(infoEntity.getClientInfoEntity().getCustomerNum());
                break;
            case R.id.btn_calculate_save:
                saveResult();
                break;
            case R.id.tv_calculate_promise_list:
                mView.intentToPromiseList();
                break;
            case R.id.btn_calculate_apply:
                if (mView.getApplyInfo(infoEntity.getPromiseApplyEntity())) {
                    if (Double.valueOf(infoEntity.getPromiseApplyEntity().getApplyRate())
                            >= Double.valueOf(infoEntity.getResultInfoEntity().getLnpTargetRate()))
                        mView.showOverDialog(false);
                    else
                        mView.showOverDialog(true);
//                        getCalculateApplyRate(infoEntity);
                }
                break;
            case R.id.tv_calculate_promise_delete:
                deletePromiseInfo(infoEntity.getLogoInfoEntity().getLogoProtocolNum());
                break;
            case R.id.tv_calculate_result_parameter:
                if (Integer.valueOf(infoEntity.getClientInfoEntity().getCustomerContributionNum()) < 0) {
                    mView.showError("客户贡献点小于0，不能发起承诺");
                    return;
                } else if (Double.valueOf(infoEntity.getResultInfoEntity().getLnpCostRate()) == Double.valueOf(infoEntity.getResultInfoEntity().getLnpCustRate())) {
                    mView.showError("您的贷款利率已达最低利率，不能进行承诺录入");
                    return;
                }
                mView.intentToParameter(infoEntity.getResultInfoEntity());
                break;
        }
    }

    private void deletePromiseInfo(String priceId) {
        mView.showLoading();
        Subscription subscribe = mModel.deletePromiseInfo(priceId).subscribe(new HttpSubscriber<HttpStrEntity>(context) {
            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onNext(HttpStrEntity entity) {
                if (entity.isSuccess()) {
                    mView.showError(entity.getData());
                    mView.hidePromiseInfo(infoEntity.getPromiseApplyEntity());
                }
            }

            @Override
            public void onError(ApiException e) {
                mView.hideLoading();
                mView.showError(e.getMessage());
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public void getCalculateApplyRate(LoanCalculateInfoEntity infoEntity) {
        mView.showLoading();
        Subscription subscribe = mModel.getCalculateApplyRate(infoEntity).subscribe(new HttpSubscriber<ApplyNextUserEntity>(context) {
            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onNext(ApplyNextUserEntity entity) {
                mView.showPersonList(entity);
            }

            @Override
            public void onError(ApiException e) {
                mView.hideLoading();
                mView.showError(e.getMessage());
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public void getApplyRateOnProcess(LoanCalculateInfoEntity infoEntity) {
        mView.showLoading();
        Subscription subscribe = mModel.getApplyRateNoProcess(infoEntity).subscribe(new HttpSubscriber<HttpStrEntity>(context) {
            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onNext(HttpStrEntity entity) {
                mView.showError(entity.getData());
                mView.intentToMain();
            }

            @Override
            public void onError(ApiException e) {
                mView.hideLoading();
                mView.showError(e.getMessage());
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public void submitNextPerson(NextPersonEntity bean) {
        mView.showLoading();
        mModel.submitNextPerson(infoEntity, bean).subscribe(new HttpSubscriber<HttpApplyResultEntity>(context) {
            @Override
            public void onCompleted() {
                mView.hideLoading();
            }

            @Override
            public void onNext(HttpApplyResultEntity entity) {
                if (entity.getSuccess().equals("true")) {
                    mView.intentToMain();
                    mView.showError("审批人选择成功");
                } else {
                    mView.showError(entity.getMsg());
                }
            }

            @Override
            public void onError(ApiException e) {
                mView.hideLoading();
                mView.showError(e.getMessage());
            }
        });
    }

    @Override
    public void checkPromise(String custId) {
        Subscription subscribe = mModel.checkPromise(custId).subscribe(new HttpSubscriber<HttpCheckProEntity>(context) {
            @Override
            public void onError(ApiException e) {
                mView.showError(e.getMessage());
            }

            @Override
            public void onCompleted() {

            }

            @Override
            public void onNext(HttpCheckProEntity httpCheckProEntity) {
                if (httpCheckProEntity.isSuccess()) {
                    if (httpCheckProEntity.getData().getIsFinish().equals("true")) {
                        mView.intentToPromise(AppConstant.LOAN_PROMISE_REQUEST);
                    } else {
                        mView.showError("有未完成的以往承诺调节，暂不能发起承诺");
                    }
                }
            }
        });
        subscription.add(subscribe);

    }

    @Override
    public void start() {
        getLogoInfo();
    }

    @Override
    public void onRecycle() {
        subscription.clear();
    }
}